import functools


class Solution(object):
    def minKnightMoves(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        x = abs(x)
        y = abs(y)
        final = {(0, 0): 0, (0, 1): 3, (0, 2): 2, (1, 1): 2, (1, 2): 1, (2, 2): 4}
        left = x - 3
        right = x + 3
        up = y + 3
        down = y - 3

        @functools.cache
        def search(start, end):
            x1 = min(abs(x - start), abs(y - end))
            y1 = max(abs(x - start), abs(y - end))
            if (x1, y1) in final:
                return final[(x1, y1)]
            else:
                min_value = float('inf')
                if start < x:
                    if end < y:
                        min_value = min(min_value, search(start + 2, end + 1) + 1)
                        min_value = min(min_value, search(start + 1, end + 2) + 1)
                    else:
                        min_value = min(min_value, search(start + 2, end - 1) + 1)
                        min_value = min(min_value, search(start + 1, end - 2) + 1)
                else:
                    if end < y:
                        min_value = min(min_value, search(start - 1, end + 2) + 1)
                        min_value = min(min_value, search(start - 2, end + 1) + 1)
                return min_value

        return search(0, 0)


data = Solution()
x = 2
y = 1
print(data.minKnightMoves(x, y))
